'use strict';

/** 
 * @Author   yh
 * @DateTime 2018-05-10
 * @Description [小程序http请求封装]
 */
const utils = require("../utils/util.js");
const router = require("../utils/navigator.js");

const Fly = require("./wx.umd.min.js");
//Create an instance of Fly
const fly = new Fly();

const DEFAULT_REQUEST_OPTIONS = {
    method: 'GET', //请求方法， GET 、POST ...
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json' // 默认值
    }, //请求头
    baseURL: '', //请求基地址
    //是否自动将Content-Type为“application/json”的响应数据转化为JSON对象，默认为true
    parseJson: true,
    timeout: '60000' //超时时间
}

//实例级配置
fly.config = DEFAULT_REQUEST_OPTIONS;

//多请求同时进行时的全局loading配置
let requestCount = 0;

function showLoading(title) {
    if (requestCount === 0) {
        wx.showLoading({
            title,
            mask: true
        });
    }
    requestCount++;
}

function hideLoading() {
    if (requestCount <= 0) return;
    requestCount--;
    if (requestCount === 0) {
        //合并一定间隔时间内请求的 loading
        utils.debounce(function() { wx.hideLoading() }, 400)()
    }
}

function showToast(opt) {
    wx.showToast({
        title: opt.title,
        icon: opt.icon || 'none',
        duration: opt.duration || 2000,
    })
    if (opt.callback && 'function' === typeof opt.callback) {
        setTimeout(function() {
            opt.callback()
        }, opt.duration || 1000)
    }
}

// Add interceptors
fly.interceptors.request.use((config, promise) => {
    if (config.loading && config.loading.show) showLoading(config.loading.text);
    return config;
})

fly.interceptors.response.use(
    (response, promise) => {
        // console.log(response)
        if (response.request.loading && response.request.loading.show) hideLoading();

        if (typeof(response.data) == 'string' && response.data != '') {
            response.data = JSON.parse(response.data);
        }

        if (response.data.status == 404) {
            showToast({
                title: response.data.msg || 'interface not defined'
            })
            return Promise.reject('接口未定义');
        } else if (response.data.status == 405) {
            //登录失效
            showToast({
                title: response.msg || '登录失效',
                callback: function() {
                    wx.clearStorage({
                        success() {
                            router.reLaunch('/pages/login/index');
                        }
                    })
                }
            });
            return Promise.reject(response.data);
        } else {
            if (response.request.customResponse) {
                // return response.data;
                return Promise.resolve(response.data);
            } else {
                if (response.data.status == 1) {
                    // return response.data;
                    // return Promise.resolve(response.data);
                } else {
                    // console.log(response)
                    showToast({
                        title: response.data.msg || '请求失败'
                    })
                    // return Promise.reject(response.data);
                }
                return Promise.resolve(response.data);
            }
        }
    },
    (err, promise) => {
        if (err.request.loading && err.request.loading.show) hideLoading();

        const errState = {
            0: '网络错误',
            1: '请求超时',
            2: '文件下载成功，但保存失败', //此错误只出现node环境下
        };

        const status = +err.status;

        if ([0, 1, 2].includes(status)) {
            showToast({
                title: errState[status]
            })
        } else if (status >= 200) {
            //具体状态值视情况自行细分
            showToast({
                title: '出错啦！请稍后再试试哦～'
            })
        }
        return Promise.reject(err);
    }
)

/** 
 * @param    {String}   url    [请求地址]
 * @param    {Object}   data   [请求数据]
 * @param    {Object}   options [请求配置信息]
 * @param    {Boolean}  customResponse [自定义处理返回值]
 * @return   {[type]}          [http实例]
 */
const REQUEST_API = (url = '', data = {}, options) => {

    const DEFAULT_CONFIG_OPTIONS = {
        method: 'GET',
        loading: {
            show: true,
            text: '载入中...'
        },
        customResponse: false
    }

    let config = utils.deepMerge(DEFAULT_CONFIG_OPTIONS, options)

    return new Promise((resolve, reject) => {

        fly.request(url, data, config)
            .then(res => {
                resolve(res);
                return false;
            })
            .catch(err => {
                reject(err);
            });
    });
}

module.exports = REQUEST_API;